<template>
  <div class="page-list-body">
    <el-row>
      <el-col :span="isLayoutLeft?12:24">
        <div class="page-iframe">
          <div>
            <iframe id="pagePreviewIframe" :width="pageObj.width"
                    :height="pageObj.height"
                    :src="curProjectPath+pageObj.path"
                    :title="pageObj.name"></iframe>
          </div>
        </div>
      </el-col>
      <el-col :span="isLayoutLeft?12:24">
        <div class="page-base-body">
          <el-row :gutter="32">
            <el-col :span="isLayoutLeft?24:12">
              <div>
                <div class="title">页面名称：{{pageObj.name||''}}</div>
                <div class="title">页面路由：{{pageObj.path||''}}</div>
                <div class="title">页面所属模块：
                  <div style="display: inline-block;"
                    v-if="pageObj&&pageObj.modules&&(pageObj.modules.indexOf('engineer')>-1||pageObj.modules.indexOf('flood_prevention')>-1||pageObj.modules.indexOf('river')>-1||pageObj.modules.indexOf('water_resource')>-1||pageObj.modules.indexOf('geological_section')>-1)">
                    <el-tag size="mini"
                            v-if="pageObj&&pageObj.modules&&pageObj.modules.indexOf('engineer')>-1">
                      项目工程
                    </el-tag>
                    <el-tag size="mini" type="success"
                            v-if="pageObj&&pageObj.modules&&pageObj.modules.indexOf('flood_prevention')>-1">
                      智慧防汛
                    </el-tag>
                    <el-tag size="mini" type="info"
                            v-if="pageObj&&pageObj.modules&&pageObj.modules.indexOf('river')>-1">
                      智慧河湖
                    </el-tag>
                    <el-tag size="mini" type="warning"
                            v-if="pageObj&&pageObj.modules&&pageObj.modules.indexOf('water_resource')>-1">
                      智慧水资
                    </el-tag>
                    <el-tag size="mini" type="danger"
                            v-if="pageObj&&pageObj.modules&&pageObj.modules.indexOf('geological_section')>-1">
                      地质剖面
                    </el-tag>
                  </div>
                  <el-tag size="mini" type="info" v-else>其他</el-tag>
                </div>
                <div class="title">页面描述：{{pageObj.description||''}}</div>
                <div class="title">页面宽高：{{(pageObj.width||0) + '*'
                  +(pageObj.height||0)}}
                </div>
                <h4>Web向Unity传参</h4>
                <div class="unity-socket-info-div">
                  Web向Unity传参打印：{{toWebStr}}
                </div>
              </div>
            </el-col>
            <el-col :span="isLayoutLeft?24:12">
              <div>
                <h4>Unity向Web传参：</h4>
                <el-form ref="toUnityForm" label-width="120px">
                  <el-form-item label="managerType">
                    <el-input v-model="managerType"></el-input>
                  </el-form-item>
                  <el-form-item label="methodName">
                    <el-input v-model="methodName"></el-input>
                  </el-form-item>

                  <el-form-item label="parameterData">
                    <page-add-params :from="from"
                                     :data-list="parameterDataList"
                                     @updateDataList="updateParameterDataList"
                    ></page-add-params>
                  </el-form-item>
                </el-form>
                <el-button type="primary" @click="submitToUnityNews">提交
                </el-button>
                <div class="unity-socket-info-div">
                  Unity向Web传参打印：{{toUnityStr}}
                </div>
              </div>
            </el-col>
          </el-row>
        </div>
      </el-col>
    </el-row>
    <div>
      <h4>Unity向Web传参:</h4>
      <el-table :data="pageObj.toWeb||[]" style="width: 100%"
                ref="myTable">
        <el-table-column v-for="(item,ind) in dataTableList" :key="ind"
                         :label="item.label"
                         :prop="item.key" :align="item.align"
                         :min-width="item.minWidth">
          <template slot-scope="scope">
            <div v-if="!item.isCustom"
                 style="white-space: pre-line;">
              {{scope.row[item.key]||item.defaultText }}
            </div>
            <div class="text-ellipsis-2"
                 style="white-space: pre-line;"
                 v-if="item.isCustom&&item.key!='ind'&&item.key!='params'&&item.key!='description'">
              {{scope.row[item.key]||item.defaultText }}
            </div>
            <div class="text-ellipsis-2"
                 v-if="item.isCustom&&item.key=='ind'">
              {{ scope.$index +1}}
            </div>
            <div v-if="item.isCustom&&item.key=='params'"
                 style="white-space: pre-line;">
              {{
              scope.row[item.key]?JSON.stringify(scope.row[item.key]):item.defaultText}}
            </div>
            <div v-if="item.isCustom&&item.key=='description'"
                 style="white-space: pre-line;">
              <page-obj-show :from="from"
                             :data-obj="scope.row[item.key]"
              ></page-obj-show>
            </div>
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" min-width="216"
                         align="center">
          <template slot-scope="scope">
            <el-button type="success" size="small"
                       @click="readToNewsData(scope.row)">快速代入测试值
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <h4>Web向Unity传参:</h4>
      <el-table :data="pageObj.toUnity||[]" style="width: 100%"
                ref="myTable">
        <el-table-column v-for="(item,ind) in dataTableList" :key="ind"
                         :label="item.label"
                         :prop="item.key" :align="item.align"
                         :min-width="item.minWidth">
          <template slot-scope="scope">
            <div v-if="!item.isCustom"
                 style="white-space: pre-line;">
              {{scope.row[item.key]||item.defaultText }}
            </div>
            <div class="text-ellipsis-2"
                 style="white-space: pre-line;"
                 v-if="item.isCustom&&item.key!='ind'&&item.key!='params'&&item.key!='description'">
              {{scope.row[item.key]||item.defaultText }}
            </div>
            <div class="text-ellipsis-2"
                 v-if="item.isCustom&&item.key=='ind'">
              {{ scope.$index +1}}
            </div>
            <div v-if="item.isCustom&&item.key=='params'"
                 style="white-space: pre-line;">
              {{
              scope.row[item.key]?JSON.stringify(scope.row[item.key]):item.defaultText}}
            </div>
            <div v-if="item.isCustom&&item.key=='description'"
                 style="white-space: pre-line;">
              <page-obj-show :from="from+'_toWeb'"
                             :data-obj="scope.row[item.key]"
              ></page-obj-show>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
  import PageAddParams from '../components/page-add-params.vue';
  import PageObjShow from '../components/page-obj-show.vue';
  import {Message} from "element-ui";
  import StringUtils from "../../utils/string";
  // preview 主要预览某个页面，模仿unity传参，并将unity接收到的前台传值参数给展示出来
  export default {
    name: "preview",
    components: {
      PageAddParams,
      PageObjShow,
    },
    data() {
      return {
        from: 'preview',
        curProjectPath: '',
        isLayoutLeft: true,
        previewIframeObj: null,
        pageObj: {},
        managerType: '',
        methodName: '',
        parameterData: '',
        parameterDataObj: {},
        toUnityStr: '',
        toWebStr: '',
        parameterDataList: [],
        dataTableList: [
          {
            key: 'ind',
            label: '序号',
            align: 'center',
            minWidth: '100',
            defaultText: '--',
            isCustom: true,
          },
          {
            key: 'title',
            label: '标题',
            align: 'center',
            minWidth: '120',
            defaultText: '--',
            isCustom: false,
          },
          {
            key: 'params',
            label: '传值参数',
            align: 'center',
            minWidth: '120',
            defaultText: '--',
            isCustom: true,
          },
          {
            key: 'description',
            label: 'parameterData说明',
            align: 'center',
            minWidth: '120',
            defaultText: '--',
            isCustom: true,
          },
        ],
      }
    },
    mounted() {
      let locationHref = window.location.href;
      let hrefArr = locationHref.split('/unity/');
      this.curProjectPath = hrefArr[0] + '/unity';
      this.pageObj = this.$route.query.data || null;
      if (!this.pageObj.hasOwnProperty('name')) {
        let ttStr = localStorage.getItem('previewPageItem');
        let tt = StringUtils.toJson(ttStr);
        this.pageObj = tt.data;
      }
      let bodyWidth = document.body.offsetWidth;
      // if (this.pageObj.hasOwnProperty('width') && this.pageObj.hasOwnProperty(
      //   'height') && (this.pageObj.width > (this.pageObj.height * 2))) {
      if (this.pageObj.hasOwnProperty('width') && (this.pageObj.width
        > (bodyWidth / 2))) {
        this.isLayoutLeft = false;
      } else {
        this.isLayoutLeft = true;
      }
      this.$nextTick(() => {
        this.previewIframeObj = document.getElementById('pagePreviewIframe');
      });

      window.addEventListener('message', (e) => {
        this.toWebStr = StringUtils.toStr(e.data);
      }, false);
      document.addEventListener('keydown', (e) => {
        let key = window.event.keyCode;
        if (key == 13) {
          if (this.managerType != '' && this.methodName != '') {
            this.submitToUnityNews();
          }
        }
      });
    },
    methods: {
      updateParameterDataList(params) {
        let from = params.from || '';
        let list = params.list || [];
        if (from == this.from) {
          this.parameterDataList = list;
        }
      },
      submitToUnityNews() {
        if (this.managerType == '') {
          Message.warning('请输入参数managerType');
          return;
        }
        if (this.methodName == '') {
          Message.warning('请输入参数methodName');
          return;
        }
        let paramsDataObj = {};
        for (let i = 0; i < this.parameterDataList.length; i++) {
          paramsDataObj[this.parameterDataList[i].key] = this.parameterDataList[i].value;
        }
        let parameterDataStr = StringUtils.toStr(paramsDataObj);
        this.parameterData = parameterDataStr;
        let params = {
          "managerType": this.managerType,
          "methodName": this.methodName,
          "parameterData": parameterDataStr,
        };
        this.toUnityStr = StringUtils.toStr(params);
        if (this.previewIframeObj) {
          console.log('=======', this.previewIframeObj, this.toUnityStr)
          this.previewIframeObj.contentWindow.postMessage(params, '/');
        }
      },
      readToNewsData(item) {
        this.managerType = item.params.managerType || '';
        this.methodName = item.params.methodName || '';
        this.parameterData = item.params.parameterData || '';
        let paramesObj = StringUtils.toJson(this.parameterData);

        let getArrayResList = (list) => {
          let rList = [];
          for (let i = 0; i < list.length; i++) {
            let p = list[i];
            let pArr = [];
            for (const pKey in p) {
              let pOne = {
                key: '',
                value: '',
                type: '',
                list: '',
              };
              pOne.key = pKey;
              pOne.value = Array.isArray(p[pKey]) ? p[pKey] : (p[pKey] + '');
              pOne.type = Array.isArray(pOne.value) ? 'array' : 'string';
              pOne.list = Array.isArray(pOne.value) ? getArrayResList(
                pOne.value) : '';
              pArr.push(pOne);
            }
            rList.push(pArr);
          }
          return rList;
        };
        let getObjectResList = (obj) => {
          let resultList = [];
          for (const objKey in obj) {
            let tVal = obj[objKey];
            let tType = (typeof tVal);
            if (tType == "object") {
              tType = Array.isArray(tVal) ? 'array' : 'object';
            }
            tType = ['array', 'object', 'string'].indexOf(tType) > -1 ? tType
              : 'string';

            let tt = {
              value: tVal,
              key: objKey,
              type: tType,
            };

            let isCurTypeArray = Array.isArray(tVal);
            // let tt = {
            //   value: tVal,
            //   key: objKey,
            //   type: isCurTypeArray ? 'array' : (typeof tVal == "object"
            //     ? 'object' : 'string'),
            // };
            if (tType == 'array') {
              // 是数组
              Object.assign(tt, {list: getArrayResList(tVal)});
            } else if (tType == 'string') {
              Object.assign(tt, {list: ''});
            } else if (tType == 'object') {
              Object.assign(tt, {list: getObjectResList(tVal)});
            }
            resultList.push(tt);
          }
          return resultList;
        };

        this.parameterDataList = getObjectResList(paramesObj);
      },
    },
  }
</script>

<style lang="scss" scoped>
  @import url("../../assets/css/unity.scss");

  .page-list-body {
    -webkit-touch-callout: default;
    -webkit-user-select: text;
    -moz-user-select: text;
    -ms-user-select: text;
    user-select: text;
  }

  .unity-socket-info-div {
    border: 1px solid #e5e5e5;
    padding: 10px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    margin: 16px auto;

  }
</style>
